<?php
/**
 * Created by PhpStorm.
 * User: liuxiaojie
 * Date: 2019-03-10
 * Time: 22:51
 */

namespace app\ops\controller;

class Coupon extends Base

{

    function index()
    {
        $list = db('coupon')->where(['status'=> 1])->field('expired_type, coupon_id, name, start_time, expired_date, type, value, num, create_time')->order('coupon_id desc')->paginate(10)->each(function (&$item){
            $count = db('my_coupon')->where(['coupon_id'=> $item['coupon_id']])->count();
            $item['num'] = $item['num'] - $count > 0 ?$item['num'] - $count:0;
            return $item;
        });

        $this->assign('list', $list);
        return $this->fetch();
    }

    function edit($id = 0)
    {
        $post = request()->post();
        if($post)
        {
            if($post['coupon_id'])
            {
                db('coupon')->update($post);
            }else{
                unset($post['coupon_id']);
                db('coupon')->insert($post);
            }
            return success([]);
        }else{
            $data = db('coupon')->where(['coupon_id'=> $id])->find();
            $this->assign('data', $data);
            return $this->fetch();
        }
    }


    function delete()
    {
        $id = request()->post('id');
        db('games')->where(['game_id'=> $id])->update(['status'=> 0]);
        return success([]);
    }

    function detail()
    {
        $id = request()->param('id');
        $data = db('coupon')->where(['coupon_id'=> $id])->find();
        $company = db('company')->where(['id'=> $data['uid']])->value('name');
        $this->assign('data', $data);
        $this->assign('company', $company);
        return $this->fetch();
    }
}